package cn.chiship.bs.api.core.exception;


import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.enums.BaseResultEnum;
import cn.chiship.sdk.core.exception.ExceptionUtil;
import cn.chiship.sdk.core.exception.model.CommonExceptionVo;
import cn.chiship.sdk.core.util.StringUtil;
import org.springframework.http.converter.HttpMessageNotReadableException;

/**
 * @author lijian
 * 框架类异常
 */
public class FrameworkErrorException extends RuntimeException {
    private Integer errorCode;
    private String errorMessage;
    private String errorLocalizedMessage;

    public FrameworkErrorException() {
    }


    public FrameworkErrorException(Throwable cause) {
        super(null, cause);
        FrameworkExceptionEnum frameworkExceptionEnum = null;

        if (cause instanceof HttpMessageNotReadableException) {
            frameworkExceptionEnum = FrameworkExceptionEnum.HTTP_MESSAGE_NOT_READABLE;
        }
        if (!StringUtil.isNull(frameworkExceptionEnum)) {
            if (StringUtil.isNull(cause)) {
                this.errorLocalizedMessage = frameworkExceptionEnum.getErrorMessage();
            } else {
                this.errorLocalizedMessage = ExceptionUtil.getErrorLocalizedMessage(cause);
            }
            this.errorMessage = frameworkExceptionEnum.getErrorMessage();
            this.errorCode = frameworkExceptionEnum.getErrorCode();
        }
    }


    public BaseResult formatException() {
        return formatException(null);
    }

    public BaseResult formatException(String requestId) {
        /**
         * 注意 BaseResult.error()第一个参数根据不同的分类异常返回一级错误码
         * 一级错误码在 @see com.dianll.common.lib.core.base.BaseResultEnum 中定义
         *
         */
        return BaseResult.error(
                BaseResultEnum.SYSTEM_ERROR,
                new CommonExceptionVo(
                        this.getErrorCode(),
                        this.getErrorMessage(),
                        requestId,
                        null,
                        this.getErrorLocalizedMessage()
                )
        );
    }

    public Integer getErrorCode() {
        return errorCode;
    }

    public String getErrorMessage() {
        return errorMessage;
    }


    public String getErrorLocalizedMessage() {
        return errorLocalizedMessage;
    }

}
